package com.tech.zhidengxian.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author Ljh
 * @date 2023/5/6 16:38
 * @description
 **/
public class QrCodeUtil {
    /**
     * 生成二维码
     * @param filePath 需要存储到的位置
     * @param content 二维码中包含的内容
     * @param width 二维码的宽度
     * @param height 二维码的高度
     * @return fileName 返回文件的随机名称
     */
    public static String createQrCode(String filePath,String content,int width,int height){

        //如果文件夹不存在就创建文件夹
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }

        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置字符的编码
        hints.put(EncodeHintType.MARGIN, 1);//设置外边距的距离
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(Color.BLACK.getRGB(), Color.WHITE.getRGB());

            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix,matrixToImageConfig);

            String fileName = UUID.randomUUID() + ".jpg";//随机生成二维码的名称
            ImageIO.write(bufferedImage, "jpg", new File(filePath + File.separator + fileName));//将图片写到磁盘

            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
